import { useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import TooltipContainer from "./TooltipContainer";

type targetRect = {
  left: number;
  top: number;
  right: number;
  bottom: number;
};

export default function Tooltip({
  children,
  targetRect,
}: {
  children: React.ReactNode;
  targetRect: targetRect | null;
}) {
  const ref = useRef<HTMLDivElement>(null);
  const [tooltipHeight, setTooltipHeight] = useState(0);

  useLayoutEffect(() => {
    const rect = ref.current?.getBoundingClientRect();
    console.log(rect?.height);
    rect && setTooltipHeight(rect.height);
  }, []);

  let tooltipX = 0;
  let tooltipY = 0;
  if (targetRect !== null) {
    tooltipX = targetRect.left;
    tooltipY = targetRect.top - tooltipHeight;
    if (tooltipY < 0) {
      // 它不适合上方，因此把它放在下面。
      tooltipY = targetRect.bottom;
    }
  }

  return createPortal(
    <TooltipContainer x={tooltipX} y={tooltipY} contentRef={ref}>
      {children}
    </TooltipContainer>,
    document.body
  );
}
